import _ from "lodash";
import { UserEntity } from "./UserEntity";
import { LogicServer } from "../../LogicServer";
import { RoomManager } from "./RoomManager";
import { UserManager } from "./UserManager";
import { RobotManager } from "../robot/RobotManager";
import { EnumCacheGroup } from "../../../../common/enum/EnumCacheGroup";
import { EnumErrorCode } from "../../../../common/enum/EnumErrorCode";
import { UserData } from "../../../../common/model/UserData";
import { EnumProtocolType } from "../../../../common/protocols/EnumProtocolType";
import { CS_Login, SC_Login } from "../../../../common/protocols/Proto_Login";
import { CS_Register } from "../../../../common/protocols/Proto_Register";
import { CacheComponent } from "../../../../framework/service/Components/CacheComponent";
import { IMsg } from "../../../../framework/service/Components/WorkOrderInfo";
import { Tools } from "../../../../framework/utils/Tools";
import { InstanceBasic } from "../../../../framework/controller/InstanceBasic";
import ConstRobotConfig from "../robot/ConstRobotConfig";
import { ConfigManager } from "../../../../common/config/ConfigManager";


export class LogicCenter extends InstanceBasic {

    private static _instance: LogicCenter = null;

    public static get inst(): LogicCenter {
        if (this._instance === null) {
            this._instance = new LogicCenter();
        }
        return this._instance;
    }


    public init(): void {
        this.setUpdateEnabled(true, 1000);

        
        setTimeout(()=>{
            RoomManager.inst.init();
        },3000);

        setTimeout(() => {
            RobotManager.inst.init();
        }, 4000);

        ConfigManager.inst.load();

    }

    public commingRequest(req: IMsg, userEnity: UserEntity): void {

        RoomManager.inst.commingRequest(req, userEnity);
        UserManager.inst.commingRequest(req, userEnity);

    }



    public async receiveTCPMessage(msg: IMsg, connection: any): Promise<void> {

        switch (msg.cmdid) {
            case EnumProtocolType.CS_Login: {
                const cs: CS_Login = <CS_Login>msg;

                const sc: SC_Login = new SC_Login();

                const cacheComp: CacheComponent = <CacheComponent>LogicServer.entity.getComponent(CacheComponent);

                const userdata: UserData = await cacheComp.get(EnumCacheGroup.USER_DATA, cs.username);

                if (!userdata) {
                    sc.errorcode = EnumErrorCode.Account_notFound;
                    connection.sendUTF(JSON.stringify(sc));
                    return;
                }
                const oldSession: string = userdata.basic.session;
                userdata.basic.session = Tools.getUID();


                await cacheComp.set(EnumCacheGroup.USER_SESSION, userdata.basic.session, userdata, 60);

                await cacheComp.set(EnumCacheGroup.USER_DATA, userdata.basic.username, userdata);
                if (oldSession.length > 0) {
                    await cacheComp.del(EnumCacheGroup.USER_SESSION, oldSession);
                }

                if (userdata.basic.password != cs.password) {
                    sc.errorcode = EnumErrorCode.Password_Error;
                    connection.sendUTF(JSON.stringify(sc));
                    return;
                }

                if (!cacheComp) {
                    sc.errorcode = EnumErrorCode.RPCComponentNotFound;
                    connection.sendUTF(JSON.stringify(sc));
                    return;
                }

                sc.session = userdata.basic.session;
                sc.userid = userdata.uid;
                sc.gamedata = userdata.gameData;


                let userEnity = UserManager.inst.getUser(userdata.uid);

                if (!userEnity) {
                    userEnity = new UserEntity();
                    userEnity.setData(userdata);
                    UserManager.inst.addUser(userEnity);
                }


                //**这里标记判断是否是机器人 */ */
                _.each(ConstRobotConfig, config => {
                    userEnity.isRobot = userEnity.data.basic.username == config.username

                });

                connection.userEntity = userEnity;
                //**这里需要绑定socket*/
                userEnity.setConnection(connection);
                connection.disconnected = () => {
                    userEnity.disconnected();
                };

                connection.sendUTF(JSON.stringify(sc));

                break;

            }
            case EnumProtocolType.CS_Register: {

                const cs: CS_Register = <CS_Register>msg;

                const sc: SC_Login = new SC_Login();

                const cacheComp: CacheComponent = <CacheComponent>LogicServer.entity.getComponent(CacheComponent);

                const userdata: UserData = await cacheComp.get(EnumCacheGroup.USER_DATA, cs.username);

                if (userdata) {
                    sc.errorcode = EnumErrorCode.Account_Exist;
                    connection.sendUTF(JSON.stringify(sc));
                    return;
                }

                const user: UserData = new UserData();
                user.basic.username = cs.username;
                user.basic.password = cs.password;
                sc.userid = user.uid;
                await cacheComp.set(EnumCacheGroup.USER_DATA, cs.username, user);
                await cacheComp.set(EnumCacheGroup.USERID_TO_USERNAME, user.uid, cs.username);
                connection.sendUTF(JSON.stringify(sc));
                break;
            }
            default: {

                if (connection.userEntity) {
                    this.commingRequest(msg, connection.userEntity);
                }

                break;
            }
        }
    }



    public update(dt: number): void {
        RoomManager.inst.update(dt);
        UserManager.inst.update(dt);
        RobotManager.inst.update(dt);
    }
}